#! /usr/bin/env python
# Mathtex command line utility
from mathtex.mathtex_main import Mathtex
from mathtex.fonts import BakomaFonts, StixFonts, StixSansFonts, UnicodeFonts
from optparse import OptionParser
from tempfile import mkstemp
import os, sys

def print_dimensions(m):
    print '[%.2f, %.2f, %.2f]' % (m.width, m.height, m.depth)

# Configure the command line argument parser
arg_parser = OptionParser()

# DPI option
arg_parser.add_option('-d', '--dpi', dest='dpi', type='int',
                      default=100, help='dpi to render the equation at')

# Fontset to use
arg_parser.add_option('-f', '--fontset', dest='fontset', type='choice',
                      choices=['bakoma', 'cm', 'stix', 'stixsans', 'unicode'],
                      default='cm', help='fonts to render the equation with')

# Output format
arg_parser.add_option('-j', '--format', dest='format', default='auto',
                      help='file format to render the equation to')

# Unicode fonts to use
arg_parser.add_option('-u', '--unicode-fonts', dest='fontlist', default='',
                      help='unicode fonts to use, in the form of style=font,..., e.g. rm=times,sf=arial')

# Font size to use
arg_parser.add_option('-x', '--font-size', dest='fontsize', type='float',
                      default=12.0, help='base font size')

# Default font style to use
arg_parser.add_option('-s', '--default-style', dest='style',
                      type='choice', choices=['rm', 'it'], default='it',
                      help='default character style to use')

# If to output bounding information or not
arg_parser.add_option('-b', '--print-dimensions', dest='dim', default=False,
                      action='store_true', help='print the dimensions for the equation')

(options, args) = arg_parser.parse_args()

# Sanity checks
if options.fontset == 'unicode' and options.fontlist == '':
    arg_parser.error('font list required to use unicode fonts')
elif options.fontset != 'unicode' and options.fontlist != '':
    arg_parser.error('-u is only available for unicode fonts')

# Create the fontset
if options.fontset == 'bakoma' or options.fontset == 'cm':
    fonts = BakomaFonts(options.style)
elif options.fontset == 'stix':
    fonts = StixFonts(options.style)
elif options.fontset == 'stixsans':
    fonts = StixSansFonts(options.style)
elif options.fontset == 'unicode':
    # Need to parse the font list
    flatlist = options.fontlist.replace('=', ',').split(',')
    fonts = UnicodeFonts(**dict(zip(flatlist[::2], flatlist[1::2])))

# Normal mode
if len(args) == 1 or len(args) == 2:
    if len(args) == 1:
        expr = raw_input()
    else:
        expr = args[1]

    try:
        m = Mathtex(expr, fonts, options.fontsize, options.dpi,
                    options.style)
        m.save(args[0], options.format)
    except ValueError, err:
        print "Parse Error:"
        print '\t' + "\n\t".join(str(err).split('\n'))
        sys.exit(1)

    if options.dim:
        print_dimensions(m)
# Neither, enter persistent mode
else:
    # Default to PNG
    if options.format == 'auto':
        options.format = 'png'

    while True:
        expr = raw_input()

        if expr == '':
            break

        # Create a temp file
        fd, name = mkstemp(suffix='.mathtex.' + options.format)
        os.close(fd)

        # Eval the expression
        m = Mathtex(expr, fonts, options.fontsize, options.dpi,
                    options.style)
        m.save(name, options.format)

        print name

        if options.dim:
            print_dimensions(m)